package app.controllers;

import app.Const;
import app.constant.OrderConstant;
import app.kit.CommonKit;
import app.models.order.Order;
import app.services.OrderService;
import bank.BankService;
import bank.resp.MerchantAccntRspDto;
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.plugin.activerecord.Model;
import goja.StringPool;
import goja.Validator;
import goja.mvc.Controller;
import goja.rapid.datatables.DTCriterias;
import goja.rapid.db.Condition;
import goja.security.shiro.AppUser;
import goja.security.shiro.Securitys;
import goja.tuples.Pair;
import org.apache.commons.lang3.math.NumberUtils;
import org.joda.time.DateTime;

import static app.Const.FIELD_MEMBER;
import static app.Const.FIELD_PRODUCT;
import static bank.BankConstant.MERCHANT_PRODUCT_NO;

/**
 * <p>
 * The url merchant Controller.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
public class MerchantController extends Controller {

    /**
     * The index route.
     * the url /merchant
     * the view in index.ftl
     */
    public void index() {}


    @Before(POST.class)
    public void charging() {

        if (Securitys.isPermitted("charging")) {
            String amount = getPara("amount");
            if (!Validator.isCurrency(amount)) {
                renderAjaxFailure("请输入正确的金额格式，比如10.00");
            } else {
                String desc = getPara("desc");
                if (Strings.isNullOrEmpty(desc)) {
                    renderAjaxFailure("请输入充值说明");
                    return;
                }
                AppUser<Model> login = Securitys.getLogin();
                Order order = OrderService.me.buildOrder(0, 0, "融理平台", MERCHANT_PRODUCT_NO, StringPool.EMPTY, OrderConstant.CHARGING);
                order.set("trade_amount", amount);
                order.set("remark", "用户[" + login.getName() + "]充值，" + desc);
                try {
                    Optional<MerchantAccntRspDto> chargingAccnt = BankService.me.rechargeMerchantAccnt(DateTime.now(), order.getStr("trade_no"), NumberUtils.createBigDecimal(amount));
                    if (chargingAccnt.isPresent()) {
                        boolean ok = chargingAccnt.get().getOrderStatus() == OrderConstant.TRADE_SUCCESS;
                        if (ok) {
                            order.set(Const.FIELD_STATUS, OrderConstant.TRADE_SUCCESS);
                            renderAjaxSuccess("充值成功");
                        } else {
                            order.set(Const.FIELD_STATUS, OrderConstant.TRADE_FAILURE);
                            renderAjaxFailure(MoreObjects.firstNonNull(chargingAccnt.get().getRespMsg(), "银行接口错误"));
                        }
                    }
                } catch (Exception e) {
                    order.set(Const.FIELD_STATUS, OrderConstant.TRADE_FAILURE);
                    renderAjaxFailure("提现失败");
                } finally {
                    order.save();
                }
            }
        } else {
            renderAjaxFailure("您没有权限进行账户充值");
        }

    }

    @Before(POST.class)
    public void withdrawals() {

        if (Securitys.isPermitted("withdrawals")) {
            String amount = getPara("amount");
            if (!Validator.isCurrency(amount)) {
                renderAjaxFailure("请输入正确的金额格式，比如10.00");
            } else {
                String desc = getPara("desc");
                if (Strings.isNullOrEmpty(desc)) {
                    renderAjaxFailure("请输入提现说明");
                    return;
                }
                AppUser<Model> login = Securitys.getLogin();
                Order order = OrderService.me.buildOrder(0, 0, "融理平台", MERCHANT_PRODUCT_NO, StringPool.EMPTY,OrderConstant.WITHDRAWALS);
                order.set("trade_amount", amount);
                order.set("remark", "用户[" + login.getName() + "]提现，" + desc);
                try {
                    Optional<MerchantAccntRspDto> chargingAccnt = BankService.me.withdrawMerchantAccnt(DateTime.now(), order.getStr("trade_no"), NumberUtils.createBigDecimal(amount));
                    if (chargingAccnt.isPresent()) {
                        boolean ok = chargingAccnt.get().getOrderStatus() == OrderConstant.TRADE_SUCCESS;
                        if (ok) {
                            order.set(Const.FIELD_STATUS, OrderConstant.TRADE_SUCCESS);
                            renderAjaxSuccess("提现成功");
                        } else {
                            order.set(Const.FIELD_STATUS, OrderConstant.TRADE_FAILURE);
                            renderAjaxFailure(MoreObjects.firstNonNull(chargingAccnt.get().getRespMsg(), "银行接口错误"));
                        }
                    }
                } catch (Exception e) {
                    order.set(Const.FIELD_STATUS, OrderConstant.TRADE_FAILURE);
                    renderAjaxFailure("提现失败");
                } finally {
                    order.save();
                }
            }
        } else {
            renderAjaxFailure("您没有权限进行账户提现");
        }
    }


    public void record() {

    }

    public void recordlist() {
        DTCriterias criterias = getCriterias();
        criterias.setParam(FIELD_MEMBER, 0);
        criterias.setParam(FIELD_PRODUCT, 0);
        criterias.setParam("product_no", MERCHANT_PRODUCT_NO);

        String time_q = getPara("time");
        if (!Strings.isNullOrEmpty(time_q)) {
            Pair<DateTime, DateTime> rangeDatetime = CommonKit.rangeDatetime(time_q);
            if (rangeDatetime != null) {
                criterias.setParam("record_time", Condition.BETWEEN, new Object[]{rangeDatetime.getValue0(), rangeDatetime.getValue1()});
            }
        }

        renderDataTables(criterias, Order.class);
    }
}